/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.ladon.apm.common.convert;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 描述: List列表Converter转换接口
 *
 * @author tianyuliang
 * @version $Id: ListConverter.java, v0.1 2019/3/25
 */
@SuppressWarnings("WeakerAccess")
public class ListConverter {

    /**
     * 按Clazz转化类型
     *
     * @param src   待转换的数据源
     * @param clazz 目标类型的clazz
     * @param <S>   数据源
     * @param <D>   目标
     * @return
     */
    public static <S, D> List<D> converter(List<S> src, Class<D> clazz) {
        if (null == src) {
            return null;
        }

        // 注意: com.github.pagehelper.Page.java 继承的是ArrayList, 并不是继承LinkedList  2019-03-25 Add by tianyuliang
        // fix: java.lang.ClassCastException: java.util.LinkedList cannot be cast to com.github.pagehelper.Page
        List<D> dist = new ArrayList<>();
        if (0 == src.size()) {
            return dist;
        }

        S s = null;
        Iterator<S> iterator = src.iterator();
        while (iterator.hasNext()) {
            s = iterator.next();
            dist.add(PojoConverter.copy(s, clazz));
        }
        return dist;
    }

    /**
     * 按自定义converter接口转换类型
     *
     * @param src       待转换的数据源
     * @param converter 实现了{@link Converter}接口的自定义转换类
     * @param <S>       数据源
     * @param <D>       目标
     * @return
     */
    public static <S, D> List<D> converter(List<S> src, Converter<S, D> converter) {
        if (null == src) {
            return null;
        }

        // 注意: com.github.pagehelper.Page.java 继承的是ArrayList, 并不是继承LinkedList  2019-03-25 Add by tianyuliang
        // fix: java.lang.ClassCastException: java.util.LinkedList cannot be cast to com.github.pagehelper.Page
        List<D> dist = new ArrayList<>();
        if (0 == src.size()) {
            return dist;
        }

        S s = null;
        Iterator<S> iterator = src.iterator();
        while (iterator.hasNext()) {
            s = iterator.next();
            dist.add(converter.doConvert(s));
        }
        return dist;
    }

}
